// 解析页面
const system = require('../../utils/system.js');

Page({
  data: {
    examId: '',
    mode: '',
    statusBarHeight: 0,
    navBarHeight: 44,
    result: null,
    loading: true,
    examTitle: '',
    questions: [],
    correctNum: 0,
    wrongNum: 0,
    correctRate: 0,
    optionLabels: ['A', 'B', 'C', 'D', 'E', 'F']  // 选项标签
  },

  onLoad(options) {
    console.log('分析页面接收到的参数:', options);
    
    // 设置状态栏高度
    this.setData({
      statusBarHeight: system.statusBarHeight,
      navBarHeight: system.navBarHeight || 44,
      examId: options.examId || '',
      mode: options.mode || ''
    });
    
    // 尝试从全局数据获取结果
    try {
      const app = getApp();
      if (app.globalData && app.globalData.currentExamResult) {
        console.log('从全局数据获取结果');
        const result = app.globalData.currentExamResult;
        this.setData({
          result: result,
          examTitle: result.examTitle || '考试解析',
          loading: false
        });
        this.loadFullQuestions(result);
        return;
      }
    } catch (e) {
      console.error('从全局数据获取结果失败:', e);
    }
    
    // 如果全局数据没有，从存储中获取
    this.loadExamResult();
  },
  
  loadExamResult() {
    const { examId, mode } = this.data;
    
    // 根据模式选择不同的存储键
    const storageKey = mode === 'mistake' 
      ? 'mistakePracticeResults' 
      : mode === 'special'
        ? 'specialResults_' + examId
        : 'examResults_' + examId;
    
    console.log('尝试从存储中获取:', storageKey);
    
    try {
      const result = wx.getStorageSync(storageKey);
      console.log('获取到的结果:', result);
      
      if (result) {
        this.setData({
          result: result,
          examTitle: result.examTitle || '考试解析',
          loading: false
        });
        this.loadFullQuestions(result);
      } else if (mode === 'special') {
        // 专项模式特殊处理 - 使用模拟数据
        console.log('专项模式但没有找到结果，使用模拟数据');
        this.loadSpecialMockData(examId);
      } else {
        wx.showToast({
          title: '未找到考试结果',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('加载考试结果出错:', error);
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },
  
  loadFullQuestions(result) {
    try {
      console.log('加载题目详情:', result);
      
      // 使用result中的questions数据
      const questions = this.data.questions;
      
      // 计算正确和错误的数量
      const correctNum = questions.filter(q => q.userAnswer === q.correctAnswer).length;
      const wrongNum = questions.length - correctNum;
      const correctRate = questions.length > 0 ? Math.round((correctNum / questions.length) * 100) : 0;
      
      this.setData({
        questions: questions,
        correctNum: correctNum,
        wrongNum: wrongNum,
        correctRate: correctRate,
        loading: false
      });
      
      console.log('题目加载完成，共', questions.length, '道题');
    } catch (error) {
      console.error('加载题目详情出错:', error);
      wx.showToast({
        title: '加载题目详情失败',
        icon: 'none'
      });
    }
  },
  
  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },
  
  // 返回首页
  returnToHome() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },
  
  onShareAppMessage() {
    return {
      title: `「${this.data.examTitle}」的答题解析，学习一下！`,
      path: `/pages/exam/index?id=${this.data.examId}`,
      imageUrl: '/images/share-analysis.png' // 可以添加一个分享图片
    };
  },

  // 加载专项模式的模拟数据
  loadSpecialMockData(examId) {
    // 创建模拟数据
    const mockResult = {
      examId: examId,
      examTitle: '专项练习 ' + examId,
      totalQuestions: 10,
      correctCount: 7,
      wrongCount: 3,
      correctRate: 0.7,
      correctRateFormatted: 70,
      timeUsed: 600, // 10分钟
      answers: Array(10).fill().map((_, i) => ({
        id: i + 1,
        correct: i < 7, // 前7题正确，后3题错误
        userAnswer: String.fromCharCode(65 + Math.floor(Math.random() * 4)), // A, B, C, D
        correctAnswer: String.fromCharCode(65 + Math.floor(Math.random() * 4))
      }))
    };
    
    this.setData({
      result: mockResult,
      examTitle: mockResult.examTitle,
      loading: false
    });
    
    this.loadFullQuestions(mockResult);
  }
}) 